import cv2
import pyautogui
import numpy as np
import tkinter as tk
from tkinter import filedialog, messagebox

class App:
    def __init__(self, root):
        self.root = root
        self.root.title("Auto Moust")
        
        self.file_path = None
        
        self.upload_button = tk.Button(root, text="上传文件", command=self.upload_file)
        self.upload_button.pack(pady=5)
        
        self.start_button = tk.Button(root, text="开始", command=self.start, state='disabled')
        self.start_button.pack(pady=5)
        
        self.pause_button = tk.Button(root, text="暂停", command=self.pause, state='disabled')
        self.pause_button.pack(pady=5)
        
        self.interval_label = tk.Label(root, text="频率 (秒):")
        self.interval_label.pack(pady=5)
        
        self.interval_entry = tk.Entry(root, width=10, validate="key", validatecommand=(root.register(self.validate_interval), '%P'))
        self.interval_entry.pack(pady=5)
        self.interval_entry.insert(0, "5")
        
        self.log_text = tk.Text(root, width=50, height=10, state='disabled')
        self.log_text.pack(pady=5)
        
        self.running = False

    def validate_interval(self, value):
        return value.isdigit() or value == ""

    def upload_file(self):
        self.file_path = filedialog.askopenfilename(filetypes=[('PNG Files', '*.png')])
        if self.file_path:
            self.update_log(f"Selected file: {self.file_path}")
            self.start_button.config(state='normal')
            self.pause_button.config(state='normal')
        else:
            self.update_log("No file selected.")

    def start(self):
        if not self.file_path:
            messagebox.showwarning("Warning", "Please upload a file first.")
            return
        
        self.running = True
        self.update_log("Started.")
        self.interval_entry.config(state='disabled')
        self.process_image()

    def pause(self):
        self.running = False
        self.update_log("Paused.")
        self.interval_entry.config(state='normal')

    def process_image(self):
        if not self.running:
            return
        
        # 读取屏幕截图
        screenshot = pyautogui.screenshot()
        screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)

        # # 读取模板图像
        # template = cv2.imread(str(self.file_path), 0)
        # 读取模板图像
        with open(self.file_path, 'rb') as f:
            file_bytes = np.asarray(bytearray(f.read()), dtype=np.uint8)
            template = cv2.imdecode(file_bytes, cv2.IMREAD_GRAYSCALE)
        
        if template is None:
            print(f"Error: Unable to read the template image from {self.file_path}")
            return

        template_w, template_h = template.shape[::-1]
        # 转换截图为灰度图像
        gray_screenshot = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)

        # 匹配模板
        res = cv2.matchTemplate(gray_screenshot, template, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

        # 设置匹配阈值
        threshold = 0.8
        if max_val >= threshold:
            top_left = max_loc
            bottom_right = (top_left[0] + template_w, top_left[1] + template_h)
            center_x = top_left[0] + template_w // 2
            center_y = top_left[1] + template_h // 2
            pyautogui.doubleClick(center_x, center_y) # 双击
            self.update_log("double clicked.!")
        else:
            self.update_log(f"Image not found on the screen.")
        
        # 获取用户设置的频率
        interval = int(self.interval_entry.get()) * 1000
        self.root.after(interval, self.process_image)

    def update_log(self, message):
        self.log_text.config(state='normal')
        self.log_text.insert(tk.END, message + "\n")
        lines = self.log_text.get("1.0", tk.END).split("\n")
        if len(lines) > 10:  # 保留3行日志，加上最后一个空行
            self.log_text.delete("1.0", "2.0")
        self.log_text.config(state='disabled')

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()